import { Form, Input, Button, message as Message } from 'antd';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

import commonService from '@/api/services/commonService';
import Editor from '@/components/editor';

export default function EditorPage() {
  const [form] = Form.useForm();
  const [params, setParams] = useState({});
  const uri = 'base-property';
  const queryParams = new URLSearchParams(useLocation().search);
  const id = queryParams.get('id');

  useEffect(() => {
    commonService.getApi(uri, { domainId: id }).then((res) => {
      setParams(res);
      form.setFieldsValue({ ...res });
    });
  }, [form, id]);

  const onSubmit = async () => {
    const subData = { ...params, ...form.getFieldsValue() };
    if (id) {
      await commonService.editApi(uri, subData);
    } else {
      await commonService.addApi(uri, subData);
    }
    Message.success('操作成功');
  };

  return (
    <Form form={form} onFinish={onSubmit}>
      <Form.Item<any> label="标题" name="title" className="!mb-0">
        <Input />
      </Form.Item>
      <Form.Item<any> label="内容" name="detail" className="!mb-0">
        <Editor id="full-editor" />
      </Form.Item>
      <Button type="primary" htmlType="submit" className="ml-4">
        提交
      </Button>
    </Form>
  );
}
